package com.fingard.dsp.bank.directbank.qdcb01;

import java.util.Calendar;
import java.util.Date;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

public class QDCB01Transaction extends QDCB01Base implements ITransaction {

    //采用流处理方式
    //1、循环调用readRecord()读取一个请求明细，然后写入发银行的XML对象
    //2、发银行
    //3、循环调用XmlTextReader.read()读取一个银行返回节点，赋值返回ATS的明细对象，
    //   然后调用writeRetDetail()，写入返回ATS的明细
    public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception {
        //历史明细查询返回ATS的对象
        RetAtsTrans retAts = new RetAtsTrans(p_req7516.reqHeader);
        String tmpRespCode = "";
        String tmpRespInfo = "";
        retAts.writeStart();//写返回ATS的统一头部信息
        try {
            bsnCode = "CBE002";
            serialNo = p_req7516.reqHeader.transSeqID;
            //tmpClndrStepTo.get(Calendar.MONTH) MONTH是从0开始编的，意味着0是1月，11是12月
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_req7516.getDateFrom());

            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_req7516.getDateTo());

            int tmpNowStartRecord = 0;//总条数
            int intPageNumber = 1;//查询起始数
            int tmpNowReadedCount = 0;//已读条数
            String pagerFlag = "N";
            nextPageSearchKey = "";//首次上送时为空，之后上送已报文返回的关键字为准

            boolean tmpQryNext = true;
            while (tmpQryNext && tmpRespCode.length() == 0) {//分页查询
                XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
                //写入通用的头部节点
                writeCommonHeader(xmlWriter);
                xmlWriter.writeStartElement("ReqParam");
                xmlWriter.writeElementString("accountNo", p_req7516.actNum);
                xmlWriter.writeElementString("currencyType", convertCurToBank(p_req7516.actCur));
                xmlWriter.writeElementString("beginDate", Format.Date8Format.format(tmpCalendarFrom.getTime()));
                xmlWriter.writeElementString("endDate", Format.Date8Format.format(tmpCalendarTo.getTime()));
                xmlWriter.writeElementString("turnPageShowNum", "30");//可以为空，默认50条
                xmlWriter.writeElementString("nextPageFlag", pagerFlag);//下一页标识
                xmlWriter.writeElementString("nextPageSearchKey", nextPageSearchKey);//下一页查询关键值
                xmlWriter.writeElementClosed("ReqReserved1");
                xmlWriter.writeElementClosed("ReqReserved2");

                xmlWriter.writeEndElement();
                xmlWriter.writeEndDocument();
                String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
                //模拟银行返回
                /*tmpStrRet[0]="";
                tmpStrRet[1]="0000||#<?xml version=\"1.0\" encoding=\"GB2312\" ?><QDBankData><opRep><serialNo>1337358904</serialNo><accountNo>623170015000269</accountNo><currencyType>RMB</currencyType>\n" +
                        "<opResult><turnPageShowNum>006</turnPageShowNum><nextPageFlag>Y</nextPageFlag>\n" +
                        "<nextPageSearchKey>0000802330200079453DRMB 201812320181231354512018-05-03-13.54.51.062000016021248001*RMHVPS</nextPageSearchKey><list><row><oppositeAccNo/><out_oppositeAccNo/><oppositeAccName/><onloanFlag>D</onloanFlag><creditAmount>0.00</creditAmount><debitAmount>1021.00</debitAmount><transferDate>20180501</transferDate><transferTime>072916</transferTime><balance>2607147.42</balance><TransDesc>青岛电信</TransDesc><purpose>GBIS00049922        青岛市市政建设发展有限公司</purpose></row><row><oppositeAccNo>0</oppositeAccNo><out_oppositeAccNo>6231700150002697705</out_oppositeAccNo><oppositeAccName>谭鹏</oppositeAccName><onloanFlag>D</onloanFlag><creditAmount>0.00</creditAmount><debitAmount>6000.00</debitAmount><transferDate>20180502</transferDate><transferTime>101335</transferTime><balance>2601147.42</balance><TransDesc>活期转活期</TransDesc><purpose>伙房</purpose></row><row><oppositeAccNo/><out_oppositeAccNo>38040188000058586</out_oppositeAccNo><oppositeAccName>青岛瑞友电子科技有限公司</oppositeAccName><onloanFlag>D</onloanFlag><creditAmount>0.00</creditAmount><debitAmount>3000.00</debitAmount><transferDate>20180502</transferDate><transferTime>154239</transferTime><balance>2598147.42</balance><TransDesc>网银汇款转出</TransDesc><purpose>货款</purpose></row><row><oppositeAccNo/><out_oppositeAccNo>3803021029200111394</out_oppositeAccNo><oppositeAccName>中国联合网络通信有限公司青岛市分公司</oppositeAccName><onloanFlag>D</onloanFlag><creditAmount>0.00</creditAmount><debitAmount>10000.00</debitAmount><transferDate>20180502</transferDate><transferTime>155628</transferTime><balance>2588147.42</balance><TransDesc>网银汇款转出</TransDesc><purpose>货款</purpose></row><row><oppositeAccNo/><out_oppositeAccNo>10190206001023000599800001</out_oppositeAccNo><oppositeAccName>其他应付款-非税收入过渡户</oppositeAccName><onloanFlag>D</onloanFlag><creditAmount>0.00</creditAmount><debitAmount>124689.60</debitAmount><transferDate>20180502</transferDate><transferTime>164440</transferTime><balance>2463457.82</balance><TransDesc>网银汇款转出</TransDesc><purpose>蓝谷一期水土保持补偿费</purpose></row><row><oppositeAccNo>0</oppositeAccNo><out_oppositeAccNo>372005502018010005924</out_oppositeAccNo><oppositeAccName>青岛市市政建设发展有限公司</oppositeAccName><onloanFlag>C</onloanFlag><creditAmount>1200000.00</creditAmount><debitAmount>0.00</debitAmount><transferDate>20180503</transferDate><transferTime>135451</transferTime><balance>3663457.82</balance><TransDesc>汇兑转入</TransDesc><purpose>拨款</purpose></row></list><ReqReserved1/><ReqReserved2/></opResult></opRep></QDBankData>\n";*/
                XmlTextReader tmpBkReader;
                if (tmpStrRet[0].length() == 0) {
                    StringBuilder tmpSbMsg = new StringBuilder();
                    String returnCode = tmpStrRet[1].substring(0, tmpStrRet[1].indexOf("|", 0));
                    String returnMsg = tmpStrRet[1].substring(tmpStrRet[1].indexOf("|", 0) + 1, tmpStrRet[1].lastIndexOf("|"));
                    if (isActiveRetCode(returnCode)) {
                        tmpBkReader = loadBankRespXmlReader(tmpStrRet[1].substring(tmpStrRet[1].indexOf("<")), tmpSbMsg);
                        if (tmpBkReader != null) {
                            int tmpTotalRocords = 0;//总条数
                            if (tmpBkReader.getFirstText("/QDBankData/opRep/opResult/turnPageTotalNum") != null && tmpBkReader.getFirstText("/QDBankData/opRep/opResult/turnPageTotalNum").trim().length() > 0) {
                                tmpTotalRocords = Integer.parseInt(tmpBkReader.getFirstText("/QDBankData/opRep/opResult/turnPageTotalNum"));
                            } else if (tmpBkReader.getFirstText("/QDBankData/opRep/opResult/turnPageShowNum") != null && tmpBkReader.getFirstText("/QDBankData/opRep/opResult/turnPageShowNum").trim().length() > 0) {
                                tmpTotalRocords = Integer.parseInt(tmpBkReader.getFirstText("/QDBankData/opRep/opResult/turnPageShowNum"));
                            }
                            int tmpEachPiCount = 0;
                            if (tmpTotalRocords > 0) {
                                while (tmpBkReader.read("/QDBankData/opRep/opResult/list/row")) {
                                    tmpEachPiCount++;
                                    RetAtsTransDetail tmpRetDetail = new RetAtsTransDetail();
                                    tmpRetDetail.recAccNum = tmpBkReader.readedXElement.getSingleText("oppositeAccNo");
                                    tmpRetDetail.recAccName = tmpBkReader.readedXElement.getSingleText("oppositeAccName");
                                    String creditDebitFlag = tmpBkReader.readedXElement.getSingleText("onloanFlag");//C：贷D：借
                                    if (creditDebitFlag != null) {
                                        if (creditDebitFlag.equals("D")) // 借贷标识
                                        {
                                            tmpRetDetail.cdFlag = "1";
                                        } else if (creditDebitFlag.equals("C")) {
                                            tmpRetDetail.cdFlag = "2";
                                        } else {
                                            tmpRespCode = "-1";
                                            tmpRespInfo = "借贷标志( " + creditDebitFlag + ")无法识别，请与银行核对";
                                            retAts = new RetAtsTrans(p_req7516.reqHeader);
                                            retAts.writeStart();//写返回ATS的统一头部信息
                                            retAts.writeRespCode(tmpRespCode);
                                            retAts.writeRespInfo(tmpRespInfo);
                                            retAts.writeEnd();
                                            return retAts;
                                        }
                                    }
                                    if ("1".equals(tmpRetDetail.cdFlag)) {//借
                                        tmpRetDetail.tranAmt = tmpBkReader.readedXElement.getSingleText("debitAmount");
                                    } else {//贷
                                        tmpRetDetail.tranAmt = tmpBkReader.readedXElement.getSingleText("creditAmount");
                                    }
                                    tmpRetDetail.accBal = tmpBkReader.readedXElement.getSingleText("balance").trim();//余额

                                    String transferDate = tmpBkReader.readedXElement.getSingleText("transferDate");//yyyyMMdd 系统格式为yyyy-MM-dd hh:mm:ss
                                    String tranDate = transferDate.substring(0, 4) + "-" + transferDate.substring(4, 6) + "-" + transferDate.substring(6);
                                    String transferTime = tmpBkReader.readedXElement.getSingleText("transferTime");
                                    tmpRetDetail.tranDate = tranDate;
                                    tmpRetDetail.tranTime = tranDate + " " + transferTime.substring(0, 2) + ":" + transferTime.substring(2, 4) + ":" + transferTime.substring(4);
                                    tmpRetDetail.valueDate = tmpRetDetail.tranDate;////起息日没有返回就用交易日
                                    tmpRetDetail.usage = tmpBkReader.readedXElement.getSingleText("purpose");
                                    tmpRetDetail.abstr = pickupAbstr(tmpRetDetail.usage);
                                    if (StringHelper.isNullOrEmpty(tmpRetDetail.actNum)) {
                                        tmpRetDetail.actNum = p_req7516.actNum;
                                    }
                                    retAts.writeRetDetail(tmpRetDetail);
                                }
                                tmpBkReader = loadBankRespXmlReader(tmpStrRet[1].substring(tmpStrRet[1].indexOf("<?xml")), tmpSbMsg);
                                tmpNowReadedCount += tmpEachPiCount;//总记录数
                                if ("Y".equals(tmpBkReader.getFirstText("/QDBankData/opRep/opResult/nextPageFlag"))) {
                                    pagerFlag = tmpBkReader.getFirstText("/QDBankData/opRep/opResult/nextPageFlag");
                                    nextPageSearchKey = tmpBkReader.getFirstText("/QDBankData/opRep/opResult/nextPageSearchKey");
                                }
                                else if ("N".equals(tmpBkReader.getFirstText("/QDBankData/opRep/opResult/nextPageFlag")))//本次分页查询完毕
                                {
                                    tmpQryNext = false;
                                    tmpNowReadedCount = 0;
                                    continue;
                                }
                            } else {
                                tmpQryNext = false;
                                tmpRespCode = "-1";
                                tmpRespInfo = "查询记录为空";
                            }
                        } else {
                            tmpQryNext = false;
                            tmpRespCode = "-1";
                            tmpRespInfo = tmpSbMsg.toString();
                            break;
                        }
                    } else {
                        tmpQryNext = false;
                        tmpRespCode = "-1";
                        tmpRespInfo = returnMsg;
                        break;
                    }

                } else {
                    tmpQryNext = false;
                    tmpRespCode = "-1";
                    tmpRespInfo = tmpStrRet[1];
                    break;
                }
            }
        } catch (Exception e) {
            tmpRespCode = "-1";
            tmpRespInfo = e.getMessage();
            e.printStackTrace();
        }
        if (tmpRespCode.equals("-1")) {
            retAts = new RetAtsTrans(p_req7516.reqHeader);
            retAts.writeStart();//写返回ATS的统一头部信息
            retAts.writeRespCode(tmpRespCode);
            retAts.writeRespInfo(tmpRespInfo);
        } else if (retAts.getWrittenRdCount() == 0) {
            retAts.writeRespCode("0");
            retAts.writeRespInfo("交易为空");
        }
        retAts.writeEnd();
        return retAts;
    }

    //当日明细查询调用历史明细查询方法
    public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception {
        Req7516HisTrans tmpReq7516 = new Req7516HisTrans(p_req7515.reqHeader);
        tmpReq7516.actArea = p_req7515.actArea;
        tmpReq7516.actCur = p_req7515.actCur;
        tmpReq7516.actNum = p_req7515.actNum;
        String tmpStrToday = Format.Date8Format.format(new Date());
        tmpReq7516.dateFrom = tmpStrToday;
        tmpReq7516.dateTo = tmpStrToday;
        return d_7516_HisTrans(tmpReq7516);
    }
}
